package temporay.message;

import temporay.Connection;
import temporay.SelectorThread;

import java.nio.channels.SelectionKey;

/**
 * program: io-share 
 * author: bsworld.xie 
 * create: 2021-04-20 15:26 
 * description: 
 */
public class IOWorkRequest implements Runnable {
    private SelectorThread selectorThread;

    private SelectionKey key;

    private Connection cnxn;

    public IOWorkRequest(SelectorThread selectorThread, SelectionKey key) {
        this.selectorThread = selectorThread;
        this.key = key;
        this.cnxn = (Connection) key.attachment();

    }

    @Override
    public void run() {
        if (!key.isValid()) {
            selectorThread.cleanupSelectionKey(key);
            return;
        }

        if (key.isReadable() || key.isWritable()) {
            cnxn.doIO(key);
            if (!key.isValid()) {
                selectorThread.cleanupSelectionKey(key);
                return;
            }
        }

    }
}
